{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '0'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size_layer, reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        encoder_out, encoder_state = tf.nn.dynamic_rnn(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n",
    "            inputs = tf.nn.embedding_lookup(embeddings, self.X),\n",
    "            sequence_length = self.X_seq_len,\n",
    "            dtype = tf.float32)\n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "        \n",
    "        states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "        \n",
    "        training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                sequence_length = self.Y_seq_len,\n",
    "                time_major = False)\n",
    "        training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = training_helper,\n",
    "                initial_state = states,\n",
    "                output_layer = dense)\n",
    "        training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = training_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "        self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS)\n",
    "        predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = predicting_helper,\n",
    "                initial_state = states,\n",
    "                output_layer = dense)\n",
    "        predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "        self.fast_result = predicting_decoder_output.sample_id\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-6aac78de3342>:11: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-6aac78de3342>:32: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-6aac78de3342>:35: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[28438, 30412, 19979, 31675, 19979, 19979,  4931, 18471,  3676,\n",
       "         18471,   702, 29117, 21126, 21126, 21126, 21126, 29142, 29142,\n",
       "         15474, 15474,  5174,  5174, 17397, 17397,  9708,  9708,  9708,\n",
       "          9708, 13248, 13248, 13248,  8677, 21951,  9403,  9403, 31742,\n",
       "         31742, 31742, 22656, 22656, 22656, 13919, 13919, 13919, 13919,\n",
       "         13919, 13919,  8182,  6140,  8182,  8182,  8182,  8182,  4640,\n",
       "          4640,  4640,  2338,  2338,  2338,  2338, 19056, 19056, 19056,\n",
       "         19056, 19056,  2338,  2338,  2338,  2338,  2338,  2338,  3642],\n",
       "        [11324,  3639, 17358, 21230, 20101,  2521,  2521,  1366, 22217,\n",
       "         22217, 23592, 23592, 23592, 23592, 23592, 23592, 23592,  6352,\n",
       "          6352,  6352,  6352,  6352,  6352,  6352,  6352,  6352,  1485,\n",
       "          1485, 10620, 10620, 18399, 18399,  6949,  6949, 25067,   325,\n",
       "         11187, 11187, 22271, 22271,  9057,  9057,  9057,  9057,  9057,\n",
       "          9057,  2036,  2036,  8337,  8337,  8337,  8337, 24709, 24709,\n",
       "         24709,  2381,  2838,  2838,  2838,  2838,  2838,  2838,  2838,\n",
       "         26916, 26916, 26916, 26916, 26916, 26916,  9572,  9572,  7095],\n",
       "        [15964,   212,   212, 18372, 19850, 19850,  1812,  1812,  1812,\n",
       "          1812, 23011,  4036, 23011, 12462, 12462, 12462, 12462, 12462,\n",
       "           705,   705,   705,   705,   705,   705, 23175, 23175, 23175,\n",
       "         23175, 23001, 23001, 23001, 23001, 23001, 23001, 23001, 23001,\n",
       "         23001, 23001, 26633,  1587,  5074,  5920,  5920,  5920,  5920,\n",
       "          5920,  5920,  8314,  8314,  8314,  8314,  1157,  8738, 15751,\n",
       "         15751, 15751, 15751, 15751, 15751, 29501, 29501, 23515, 23515,\n",
       "         23515, 23515,  8674, 26168, 31608, 26955, 19317, 18169, 18169],\n",
       "        [18008, 18008, 30386, 30386, 30386, 30386, 19271,  6613,  6613,\n",
       "         14650, 14650,  2407,  2407,  1374,  1374,  1672,   903,   903,\n",
       "           903, 25049, 19054, 19054, 24470, 24470,  7563,  7563,  7563,\n",
       "          9938, 17159, 17159, 17159, 26375, 26375,  1866, 17227, 17227,\n",
       "         17227, 17227, 10954,  1204,  1204, 11284, 11284, 30134, 30134,\n",
       "         30134, 30134, 25044, 22156, 22156, 22156, 22156, 22156, 22156,\n",
       "         22487, 22487, 22487, 17181, 19056, 19056, 19056, 19056,   682,\n",
       "           682,   682,   682, 31898, 24326, 24326, 13055, 12546, 12546],\n",
       "        [21112, 10447, 31905, 20350, 20350,  3935,  3935,  3935,  3935,\n",
       "          3935, 23412,  3857,  3857, 14414,  5004,  4986,  4986,  4986,\n",
       "          4986, 15958, 21338, 28082, 21480, 15377,   374,   374,  2447,\n",
       "         16906, 16906, 16906, 27895, 27895, 23389,  2201,  2201,  2201,\n",
       "         11450, 30854, 13565, 14997, 14997, 14997,   267,   267,   267,\n",
       "          7347,   779,   779,  7993,   779,   779, 17478, 14062, 14062,\n",
       "         14062,  3696,  3696,  3696,  3696, 11469, 10599, 10599, 10599,\n",
       "         10599, 10599,  2460, 24425, 11552, 11552, 10599, 10599, 21332],\n",
       "        [12400, 12400, 12720, 12720, 10943, 10943,   299,  7903,  7903,\n",
       "          3785, 11887, 11887, 11887, 11887, 20945, 20945, 14523, 20945,\n",
       "         14523, 11538, 10826, 10826, 14860, 14860, 14860, 22725, 22725,\n",
       "         24919, 16409, 16409, 16711, 16711, 16711, 19101, 16711, 16711,\n",
       "         16711, 16711, 16711, 24290, 18655, 18655, 18655, 18655, 18655,\n",
       "         13287, 13287, 13081, 13081,  8723,  8723, 26720,  1356,  1356,\n",
       "          1356,  1356, 10588, 10588, 10588,  1533,  2386,  2386,  2386,\n",
       "          2386,  2386,  2386,  2386,  2386,  2386,  2386, 16031, 16031],\n",
       "        [ 3796,  3668,  3668, 18685, 18685, 18685, 18685, 12558, 12558,\n",
       "          4548, 22690, 22690,  5043,  1587,  1587,  1587,  9472,  9472,\n",
       "         20330, 20330, 20330,  1266,   456,  1266, 30158, 30158, 30158,\n",
       "         30158, 30158, 30158, 17794,  9066, 13010, 13010, 13010, 17043,\n",
       "         30168, 15748, 15748, 15748, 15748, 15748, 25323, 25323, 25323,\n",
       "         18794, 18794, 18794, 18794, 31651,  4422, 12582, 12582, 12582,\n",
       "         22976, 22976,  2024,  2024, 26671, 26122, 26122,  3638,   317,\n",
       "           317,   317,   317,   317, 16588, 16588, 16588, 16588, 16588],\n",
       "        [29794, 29794, 21923, 30481, 30481, 12602, 22017, 22017, 22017,\n",
       "         22017, 22017, 22017,  5753,  5273,  5753,  5273,  9889,  9889,\n",
       "          5891, 21840, 21840, 21840, 21840, 31806, 18903, 18903, 18903,\n",
       "         30659, 30659, 31806, 31806, 11018, 11018, 31580, 22093, 22093,\n",
       "         22093,   516,   516, 27968, 27968, 27968, 21217, 21217, 11699,\n",
       "         21217, 21217, 21217, 21217, 31076, 31076,  3474,  3474,  3474,\n",
       "         27769, 19665, 19665, 27676, 19665, 27676, 22215, 22215, 22215,\n",
       "         21754, 21754, 21754,  5556,  5556,  5169,  5169,  5169, 11985],\n",
       "        [23549,  3037,  3037, 29815, 29815, 29815,  7993,  5421,  5421,\n",
       "          5421,  5421,  5421,  5421,  7052,  7052, 29664, 29664,  1699,\n",
       "          1699, 30012, 30012,  3407,  3407, 30064, 21308, 21308, 21308,\n",
       "         21308,  6191,  6191,  6191,  5769,  5769,  5769,  9138, 29500,\n",
       "         24331, 24331, 24331, 15260, 15260, 15260, 15260,  1357,  1357,\n",
       "          1357,  1357,  4034,  4034,  4034,  4034,  4034, 19071, 19071,\n",
       "          4034, 11158, 15088,  4034, 16448, 16448, 17541, 17541, 17541,\n",
       "         17541, 22135, 31737, 31737, 31737, 14925, 10714, 10714, 10714],\n",
       "        [19467, 19467, 19467, 19467, 24276, 24276, 24276, 24276,  7779,\n",
       "          5008, 28362,  2842,  2842,  2842, 25545,   749,   749,   749,\n",
       "         20980, 15851,  8377,  8377, 13520, 13520, 13520, 13520, 13520,\n",
       "         13520,  5289, 12334, 12334, 12334,  3608,  3608,  3608,  3608,\n",
       "          9353,  9353, 15619, 15619, 15619, 15619, 30081, 30081, 30081,\n",
       "         10815, 10815,  8348,  8348,  8348, 30514, 30514, 30514, 23608,\n",
       "         23608, 31638, 13193, 13193,  3321,  3321,  3321, 22288, 22288,\n",
       "         22288, 23221, 21424, 21424, 21424, 26446, 11256, 11256, 11256]],\n",
       "       dtype=int32), 10.372772, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:02<00:00,  2.36it/s, accuracy=0.39, cost=3.71] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.86it/s, accuracy=0.435, cost=3.29]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 4.930941, training avg acc 0.263069\n",
      "epoch 1, testing avg loss 3.546630, testing avg acc 0.394484\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.32it/s, accuracy=0.501, cost=2.68]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.93it/s, accuracy=0.511, cost=2.75]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 3.114027, training avg acc 0.444283\n",
      "epoch 2, testing avg loss 2.996409, testing avg acc 0.463157\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.578, cost=2.17]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.93it/s, accuracy=0.559, cost=2.51]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 2.572271, training avg acc 0.507747\n",
      "epoch 3, testing avg loss 2.866586, testing avg acc 0.480962\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:16<00:00,  2.31it/s, accuracy=0.616, cost=1.83]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.91it/s, accuracy=0.548, cost=2.44]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 2.263052, training avg acc 0.546822\n",
      "epoch 4, testing avg loss 2.794168, testing avg acc 0.492989\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.652, cost=1.58]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.94it/s, accuracy=0.559, cost=2.39]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.048609, training avg acc 0.575386\n",
      "epoch 5, testing avg loss 2.836713, testing avg acc 0.491978\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:14<00:00,  2.32it/s, accuracy=0.674, cost=1.44]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.90it/s, accuracy=0.543, cost=2.45]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 1.885592, training avg acc 0.597926\n",
      "epoch 6, testing avg loss 2.896173, testing avg acc 0.490702\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.689, cost=1.32]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.484, cost=2.68]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 1.755444, training avg acc 0.616665\n",
      "epoch 7, testing avg loss 3.058408, testing avg acc 0.474850\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:18<00:00,  2.30it/s, accuracy=0.741, cost=1.15]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.554, cost=2.54]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 1.655634, training avg acc 0.630843\n",
      "epoch 8, testing avg loss 2.982211, testing avg acc 0.489399\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:10<00:00,  2.33it/s, accuracy=0.739, cost=1.05]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.575, cost=2.58]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 1.577210, training avg acc 0.642356\n",
      "epoch 9, testing avg loss 3.060046, testing avg acc 0.489314\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.32it/s, accuracy=0.742, cost=0.986]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.90it/s, accuracy=0.532, cost=2.68]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.501112, training avg acc 0.654005\n",
      "epoch 10, testing avg loss 3.125565, testing avg acc 0.490250\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:16<00:00,  2.31it/s, accuracy=0.758, cost=0.942]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.94it/s, accuracy=0.543, cost=2.63]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.445707, training avg acc 0.662339\n",
      "epoch 11, testing avg loss 3.194621, testing avg acc 0.486092\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.769, cost=0.91]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.591, cost=2.5] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.387437, training avg acc 0.671823\n",
      "epoch 12, testing avg loss 3.257357, testing avg acc 0.485023\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.738, cost=1.03]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.03it/s, accuracy=0.548, cost=2.69]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.368258, training avg acc 0.673902\n",
      "epoch 13, testing avg loss 3.360435, testing avg acc 0.474507\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:17<00:00,  2.31it/s, accuracy=0.763, cost=0.896]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.527, cost=2.97]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 1.330474, training avg acc 0.680137\n",
      "epoch 14, testing avg loss 3.375649, testing avg acc 0.478569\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.755, cost=0.87]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.93it/s, accuracy=0.5, cost=3.03]  \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 1.287683, training avg acc 0.687163\n",
      "epoch 15, testing avg loss 3.472036, testing avg acc 0.477422\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:16<00:00,  2.31it/s, accuracy=0.786, cost=0.803]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.91it/s, accuracy=0.57, cost=2.73] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 1.252361, training avg acc 0.693328\n",
      "epoch 16, testing avg loss 3.499300, testing avg acc 0.481605\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.784, cost=0.794]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.575, cost=2.86]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 1.250819, training avg acc 0.692767\n",
      "epoch 17, testing avg loss 3.561963, testing avg acc 0.480502\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:14<00:00,  2.32it/s, accuracy=0.771, cost=0.835]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.94it/s, accuracy=0.522, cost=3.15]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 1.283662, training avg acc 0.685522\n",
      "epoch 18, testing avg loss 3.571134, testing avg acc 0.474561\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:13<00:00,  2.32it/s, accuracy=0.782, cost=0.811]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.532, cost=3.14]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 1.237792, training avg acc 0.694379\n",
      "epoch 19, testing avg loss 3.642445, testing avg acc 0.467723\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:14<00:00,  2.32it/s, accuracy=0.805, cost=0.73] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.516, cost=3.21]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 1.173208, training avg acc 0.707236\n",
      "epoch 20, testing avg loss 3.684494, testing avg acc 0.471464\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:23<00:00,  1.73it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.13868862"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
